'use strict';

exports.main = async (event, context) => {
  const db = uniCloud.database();
  const { taskId, action, reason = '', adminId } = event;

  if (!taskId || !action) {
    return {
      code: 400,
      msg: '缺少必要参数',
      data: null
    };
  }

  if (!['approved', 'rejected'].includes(action)) {
    return {
      code: 400,
      msg: '审核动作不正确',
      data: null
    };
  }

  try {
    const taskCollection = db.collection('taskList');
    
    // 更新任务审核状态
    const updateData = {
      audit_status: action,
      audit_time: new Date(),
      audit_admin: adminId || 'admin',
      update_time: new Date()
    };

    // 如果是拒绝，添加拒绝理由
    if (action === 'rejected') {
      if (!reason) {
        return {
          code: 400,
          msg: '拒绝审核需要填写理由',
          data: null
        };
      }
      updateData.reject_reason = reason;
      // 审核拒绝的任务可以选择隐藏（这里默认保持可见，管理员可以后续手动隐藏）
      // updateData.is_visible = false; 
    }
    
    // 如果是通过，确保任务可见
    if (action === 'approved') {
      updateData.is_visible = true;
    }

    const result = await taskCollection.doc(taskId).update(updateData);

    // 记录审核日志
    const auditLogCollection = db.collection('audit_logs');
    await auditLogCollection.add({
      target_type: 'task',
      target_id: taskId,
      action: action,
      reason: reason,
      admin_id: adminId || 'admin',
      create_time: new Date()
    });

    // 如果审核通过，可以发送通知给发布者
    if (action === 'approved') {
      // 这里可以添加推送通知逻辑
      console.log(`任务 ${taskId} 审核通过`);
    } else {
      // 审核拒绝，通知发布者
      console.log(`任务 ${taskId} 审核拒绝，理由：${reason}`);
    }

    return {
      code: 200,
      msg: '审核成功',
      data: {
        taskId: taskId,
        action: action,
        updated: result.updated
      }
    };
  } catch (error) {
    console.error('任务审核失败:', error);
    return {
      code: 500,
      msg: '审核失败',
      data: null
    };
  }
};
